package com.qyi.activemq.queue.consumer;

import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQMessage;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.jms.Session;

/**
 * @author luqi
 * @Date 2021/3/11 10:09
 * @Description TODO
 */
@Service
@Slf4j
public class MqConsumerService {

    @JmsListener(destination = "q5-normal", containerFactory = "jmsListenerContainerNormal", concurrency = "1")
    public void receiveStringQueue(String msg, ActiveMQMessage message, Session session) throws Exception {
        log.info("consumer normal:{}", msg);
        if ("error".equals(msg)) {
            throw new RuntimeException();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @JmsListener(destination = "q5-auto", containerFactory = "jmsListenerContainerAuto", concurrency = "1")
    public void receiveStringQueueAuto(String msg, ActiveMQMessage message, Session session) throws Exception {
        log.info("consumer auto:{}", msg);
        if ("error".equals(msg)) {
            log.error("rollback");
            throw new RuntimeException();
        }
    }


    @JmsListener(destination = "q5-manual", containerFactory = "jmsListenerContainerManual", concurrency = "1")
    public void receiveStringQueueManual(String msg, ActiveMQMessage message, Session session) throws Exception {
        log.info("consumer auto:{}", msg);
        if ("error".equals(msg)) {
            log.error("rollback");
            session.rollback();
        }
        session.commit();
    }

    @JmsListener(destination = "q5-ack", containerFactory = "jmsListenerContainerAck", concurrency = "1")
    public void receiveStringQueueAck(String msg, ActiveMQMessage message, Session session) throws Exception {
        log.info("consumer ack:{}", msg);
        if ("error".equals(msg)) {
            log.error("recover");
            session.recover();
        } else {
            message.acknowledge();
        }
    }

}
